export const Frag = html => {
  const tmplElem = document.createElement('template');
  tmplElem.innerHTML = html;
  return tmplElem.content;
};

/**
 * @param {import('./types').GoodsItem} item 
 * @returns {string}
 */
export const GoodsItemHTML = item => (
  `<div class="goods-item">
    <img src="${item.pic}" alt="" class="goods-pic">
    <div class="goods-info">
      <h2 class="goods-title">${ item.title }</h2>
      <p class="goods-desc">${ item.desc }</p>
      <p class="goods-sell">
        <span>月售 ${ item.sellNumber }</span>
        <span>好评率${ item.favorRate }%</span>
      </p>
      <div class="goods-confirm">
        <p class="goods-price">
          <span class="goods-price-unit">￥</span>
          <span>${ item.price }</span>
        </p>
        <div class="goods-btns">
          <i class="iconfont i-jianhao"></i>
          <span>0</span>
          <i class="iconfont i-jiajianzujianjiahao"></i>
        </div>
      </div>
    </div>
  </div>`
);

export const GoodsChildrenFrag = (onCountChange, xs) => R.reduce(
  /**
   * @param {DocumentFragment} frag 
   * @param {import('./types').GoodsItem} item 
   * @returns {DocumentFragment}
   */
  (frag, item) => {
    const identity = Frag(GoodsItemHTML(item)).children[0];
    /** @type {[HTMLButtonElement, HTMLSpanElement, HTMLButtonElement]} */
    const [decBtn, countElem, incBtn] = Array.from(identity.querySelector('.goods-btns').children);

    [
      { elem: decBtn, sign: -1 },
      { elem: incBtn, sign: +1 },
    ].forEach(o => {
      o.elem.addEventListener('click', () => {
        // 更新商品购买量状态
        // 更新商品购买量文字
        // 若商品购买量为 0 则隐藏自减按钮和数量元素
        item.count = Math.max(0, item.count + o.sign);
        countElem.innerHTML = String(item.count);
        const action = ['remove', 'add'][Number(0 < item.count)];
        identity.classList[action]('active');
        onCountChange();
      });
    });

    frag.appendChild(identity);
    return frag;
  },
  document.createDocumentFragment(),
  xs
);
